package org.jeecg.modules.readbook.controller;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;

public class Base64Decoder {
    private static final String KEY_STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    public static String decode(String input) {
        // 移除非Base64字符
        input = input.replaceAll("[^A-Za-z0-9+/=]", "");

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int index = 0;

        while (index < input.length()) {
            // 获取四个字符的索引
            int enc1 = KEY_STR.indexOf(input.charAt(index++));
            int enc2 = KEY_STR.indexOf(input.charAt(index++));
            int enc3 = KEY_STR.indexOf(input.charAt(index++));
            int enc4 = KEY_STR.indexOf(input.charAt(index++));

            // 解码三个字节
            int chr1 = (enc1 << 2) | (enc2 >> 4);
            int chr2 = ((enc2 & 0x0F) << 4) | (enc3 >> 2);
            int chr3 = ((enc3 & 0x03) << 6) | enc4;

            // 写入字节（处理无符号值）
            byteStream.write(chr1 & 0xFF);
            if (enc3 != 64) {
                byteStream.write(chr2 & 0xFF);
            }
            if (enc4 != 64) {
                byteStream.write(chr3 & 0xFF);
            }
        }

        // 转换为UTF-8字符串
        return new String(byteStream.toByteArray(), StandardCharsets.UTF_8);
    }

    // 示例用法
    public static void main(String[] args) {
        String testInput = "PHA+4oCc5Lyg6Ze777yM5YeM6ZyE6ZiB5oul5pyJ5LiA5Lu26IO95aSf56ql5o6i5aSp5py655qE56We5Zmo77yM5Lmf5q2j5piv5Zug5Li66L+Z5Lu256We5Zmo77yM5LuW5Lus5omN6IO956ql5o6i5aSp5LiL77yM55Sa6Iez5YCf5q2k5Yib6YCg5Ye656GV5aSn55qE5YeM6ZyE6ZiB44CC4oCdPC9wPg=="; // "Hello World!" 的Base64编码
        System.out.println(decode(testInput)); // 输出: Hello World!
    }
}